<template>
  <!-- 计量设备名称管理 -->
  <base-breadcrumb :title="$route.meta.title">
    <searchData :searchData="searchArr" @search="search"></searchData>
    <a-card :bordered="false">
      <list-table ref="table" :loading="loading" tableLayout="fixed" size="default"
                  :columns="columns" :request="loadData"
                  :selectConfig="{ use: true, type: 'checkbox', rowKey: 'id' }" :export-config="{
                            use: true,
                            all: exportConfig.all,
                            select: exportConfig.select,
                        }" :export-config-text="{ select: '导出选中', all: '导出全部' }"
                  :exportPermission="{select: 'qm_060_sexp_05',all: 'qm_060_aexp_06'}"
                  @exportSelect="exportSelect" @exportAll="exportAll">
        <template slot="status" slot-scope="text, record">
          {{ getArrayLable(statusArr,record.status) }}
        </template>
        <template slot="prefix">
          <a-button v-if="hideBuquBtn()" icon="plus" type="primary"
                    v-btn-permission="'qm_060_add_01'" @click="handleManage(0)">新增</a-button>
        </template>
        <template slot="actions" slot-scope="text, record">
          <MoreButton>
            <a v-btn-permission="'qm_060_loo_04'" @click="handleManage(2, record)">查看</a>
            <a v-btn-permission="'qm_060_edi_02'" v-if="hideBuquBtn()"
               @click="handleManage(1, record)">编辑</a>
            <a v-btn-permission="'qm_060_del_03'" @click="handleDel(record)"
               v-if="!getCurEquIsDeviceContext(record).length && hideBuquBtn()">删除</a>
          </MoreButton>
        </template>
      </list-table>
    </a-card>
    <!-- 计量设备名称信息弹窗 -->
    <DialogForm ref="dialogForm" :visible.sync="visible" :edit-model="editModel === 2 ? 'V' : 'E'"
                :width="700" :form="form" :isEmit="false" :api="editModel !== 0 ? api : null"
                :headerTitle="'计量设备名称信息'" :formList="formList" :rules="rules" @confirm="submitForm"
                @getForm="getFormData">
      <div slot="formFooter">
        <div class="dialog_footer_btn" v-if="editModel != 2">
          <a-button icon="plus" type="primary" @click="handleAdd">新增行</a-button>
        </div>
        <a-table rowKey="key" :columns="columnsTwo" :dataSource="dataSourceTwo" :pagination="false">
          <!-- 已关联过的规格型号不能删除和编辑 -->
          <template slot="specificationModel" slot-scope="text, record">
            <span v-if="editModel == 2">{{ text }}</span>
            <BaseInput :maxLength="100" v-else placeholder="请输入" v-model="record.specificationModel"
                       :disabled="record.type == '1'" />
          </template>
          <!-- 操作列 -->
          <template slot="actions" slot-scope="text, record">
            <a-button type="link" @click="handleDelTwo(record)" :disabled="record.type == '1'">
              删除
            </a-button>
          </template>
        </a-table>
      </div>
    </DialogForm>
  </base-breadcrumb>
</template>

<script>
import api from '@/api/quality/equipmentNameManagement' // api
import { statusArr } from '@/views/quality/equipmentManagement/constant/dictionary'
import { getArrayLable } from '@/views/quality/equipmentManagement/constant/getArrayLable'
import handleDownload from '@/views/quality/equipmentManagement/constant/downloadFile.js'
import DialogForm from '@/components/DialogForm' // 弹窗
export default {
  name: "equipmentNameManagementList",
  components: {
    DialogForm
  },
  data() {
    return {
      api,
      loading: false,
      queryParam: {},
      editModel: 0,
      form: {},
      statusArr,//状态数据字典
      exportConfig: {
        all: '计量设备名称管理列表-导出全部',
        select: '计量设备名称管理列表-导出选中',
      },
      searchArr: [
        // 搜索框
        {
          name: '设备名称',
          type: 'input',
          value: 'mdName',
        },
        {
          name: '规格名称',
          type: 'input',
          value: 'specificationModel',
        },
        {
          name: '状态',
          type: 'select',
          value: 'status',
          data: statusArr
        },
      ],
      columns: [
        {
          title: '序号',
          width: 80,
          dataIndex: 'index',
          customRender() {
            return arguments[2] + 1
          }
        },
        {
          title: '设备名称',
          ellipsis: true,
          dataIndex: 'mdName'
        },
        {
          title: '规格型号',
          ellipsis: true,
          dataIndex: 'mdModelNames'
        },
        {
          title: '单位',
          ellipsis: true,
          dataIndex: 'unit'
        },
        {
          title: '状态',
          ellipsis: true,
          dataIndex: 'status',
          scopedSlots: { customRender: 'status' }
        },
        {
          title: '操作',
          dataIndex: 'actions',
          width: '230px',
          fixed: 'right',
          scopedSlots: { customRender: 'actions' }
        }
      ],
      dataSourceTwo: [],
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        let { pageNo, pageSize } = parameter;
        let params = {
          pageNum: pageNo,
          pageSize
        };
        this.loading = true;
        const requestParameters = Object.assign({}, params, { param: this.queryParam })
        return this.api.list(requestParameters).then((res) => {
          this.loading = false;
          if (res.code === '0') {
            return { code: 200, data: res.data?.list, totalSize: res.data?.total }
          }
        }).catch((err) => {
          this.loading = false;
        })
      },
      rules: {
        mdName: [{ required: true, message: '请输入名称', trigger: 'change' }],
        unit: [{ required: true, message: '请输入编码', trigger: 'change' }],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }],
      },
      visible: false,//控制弹窗显示状态
    }
  },
  computed: {
    formList() {
      return [
        {
          keyName: 'mdName',
          type: 'BaseInput',
          disabled: this.editModel == 1 ? true : false,
          span: 12,
          label: '名称'
        },
        {
          keyName: 'unit',
          type: 'BaseInput',
          placeholder: '请输入编码',
          disabled: this.editModel == 1 ? true : false,
          span: 12,
          label: '单位'
        },
        {
          keyName: 'status',
          type: 'a-select',
          span: 12,
          label: '状态',
          data: statusArr,
          customRender(e) {
            return ['可用', '不可用'][e];
          }
        },
      ]
    },
    columnsTwo() {
      return [
        {
          title: '序号',
          width: 80,
          dataIndex: 'index',
          customRender() {
            return arguments[2] + 1
          }
        },
        {
          title: '规格型号',
          dataIndex: 'specificationModel',
          scopedSlots: { customRender: 'specificationModel' }
        },
        this.editModel != 2 && {
          title: '操作',
          dataIndex: 'actions',
          width: '160px',
          align: 'center',
          scopedSlots: { customRender: 'actions' }
        }
      ]
    }
  },
  methods: {
    /**
     * 导出选中
     * @param {Arrary} data 选中的数据
     */
    exportSelect(data) {
      const idList = data.map(item => item.id)
      const requestParameters = Object.assign({}, this.queryParam)
      requestParameters.ids = idList;
      handleDownload(this.api.exportData, requestParameters, this.exportConfig.select)
    },
    /**
    * 导出全部
    */
    exportAll() {
      handleDownload(this.api.exportData, this.queryParam, this.exportConfig.all)
    },
    /**
     * 若该设备已进行数据关联，则不能进行删除
     * @param {Object} obj 当前行数据
     */
    getCurEquIsDeviceContext(obj) {
      return obj.list.filter((e) => e.type == '1')
    },
    /**
     * 获取数组的label
     */
    getArrayLable,
    /**
    * 搜索
    * @param {Object} val 筛选项
    */
    search(val) {
      this.queryParam = { ...val }
      this.$refs.table.refresh()
    },
    /**
    * 新增/编辑/查看
    * @param {Number} type 0:新增 1:编辑 2:查看
    * @param {Object} record 当前行数据
    */
    handleManage(type, record) {
      this.editModel = type;
      this.dataSourceTwo = [];
      this.form = type ? record : {};
      this.visible = true;
    },
    /**
     * 编辑/查看时规格型号列表数据回显
     * @param {Object} data 当前行数据
     */
    getFormData(data) {
      if (data.list && data.list.length) {
        var resultArrey = data.list.map(function (item, index) {
          item = { ...item, ...{ key: `row${index + 1}` } }
          return item;
        })
        this.dataSourceTwo = resultArrey;
      }
    },
    /**
    * 删除
    * @param {Object} record 当前行数据
    */
    handleDel(record) {
      let that = this
      that.$confirm({
        title: '温馨提示',
        content: `确认删除？`,
        okText: '确认',
        cancelText: '关闭',
        onOk() {
          that.api
            .delete({ id: record.id })
            .then((res) => {
              if (res.code === '0') {
                that.$message.success('删除成功！')
                that.$refs.table.refresh(true)
              }
            })
            .catch((error) => {
              console.log(error)
            })
        }
      })
    },
    /**
    * 弹窗中表格数据项新增
    */
    handleAdd() {
      const obj = {
        key: `row${this.dataSourceTwo.length + 1}`,
        specificationModel: null,
      };
      this.dataSourceTwo.push(obj)
    },
    /**
    * 弹窗中表格数据项删除
    * @param {Object} record 当前行数据
    */
    handleDelTwo(record) {
      this.$confirm({
        title: '温馨提示',
        content: '确定删除当前规格型号？',
        onOk: () => {
          this.dataSourceTwo = this.dataSourceTwo.filter((i) => i.key !== record.key)
        }
      })
    },
    /**
     * 提交表单
     * @param {Object} form 表单数据
     */
    submitForm(form) {
      let that = this
      let name = ['create', 'edit'][that.editModel];
      let params = { ...form, ...{ list: that.dataSourceTwo } };
      // 校验规格型号表格数据
      if (that.dataSourceTwo.length > 0) {
        for (let index in that.dataSourceTwo) {
          let item = that.dataSourceTwo[index];
          let keys = {
            specificationModel: '规格型号',
          };
          for (let i in keys) {
            // 存在于校验对象，且表单值为空或不存在时提示
            if (!Object.keys(item).includes(i) || (Object.keys(item).includes(i) && !item[i])) {
              that.$message.warning(`序号${Number(index) + 1}的${keys[i]}不能为空！`)
              that.$refs.dialogForm.loading = false
              return
            }
          }
        }
      } else {
        that.$message.warning('规格型号项不能为空')
        that.$refs.dialogForm.loading = false
        return
      }
      //发送请求
      that.$refs.dialogForm.loading = true
      that.api[name](params)
        .then((res) => {
          if (res.code === '0') {
            that.$refs.dialogForm.loading = false
            that.$message.success(['添加', '编辑'][that.editModel] + '成功！')
            that.visible = false
            that.$refs.table.refresh(true)
          }
        })
        .catch((err) => {
          that.$refs.dialogForm.loading = false
        })
    },
  }
}
</script>

<style lang="less" scoped>
.dialog_footer_btn button {
  margin-bottom: 10px;
  margin-right: 8px;
}
</style>